package cn.edu.lingnan.service.impl;

import cn.edu.lingnan.Interceptor.WebInterceptor;
import cn.edu.lingnan.common.Constants;
import cn.edu.lingnan.common.Result;
import cn.edu.lingnan.entity.dto.*;
import cn.edu.lingnan.entity.Users;
import cn.edu.lingnan.entity.UsersAdmin;
import cn.edu.lingnan.entity.UsersStu;
import cn.edu.lingnan.entity.UsersTeacher;
import cn.edu.lingnan.exception.ServiceException;
import cn.edu.lingnan.mapper.AdminUserMapper;
import cn.edu.lingnan.mapper.UserMapper;
import cn.edu.lingnan.mapper.UsersStuMapper;
import cn.edu.lingnan.mapper.UsersTeacherMapper;
import cn.edu.lingnan.service.IUserService;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.log.Log;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小星星
 * @since 2023-04-07
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, Users> implements IUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UsersTeacherMapper usersTeacherMapper;
    @Autowired
    private UsersStuMapper usersStuMapper;
    @Autowired
    private AdminUserMapper adminUserMapper;


    private static final Log LOG = Log.get();





    @Override
    public UserDTO login(UserDTO userDTO) {
        Users one = getUserInfo(userDTO);
        if (one != null) {
            BeanUtil.copyProperties(one, userDTO, true);
            return userDTO;

        } else {
            throw new ServiceException(Constants.CODE_600, "用户名或密码错误");
        }
    }
    @Override
    public boolean UpdateToken(UserDTO userDTO){
        //插入token
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(Users::getUsersId,userDTO.getUsersId());
        Users users = userMapper.selectOne(queryWrapper);
        users.setToken(userDTO.getToken());
        LambdaUpdateWrapper<Users> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Users::getUsersId, userDTO.getUsersId());
        userMapper.update(users, updateWrapper);
        return true;


    }

    @Override
    public SelectDto getAll(Users users) {
        String Role = users.getUsersRole();
        SelectDto selectDto = new SelectDto();
        switch (Role){
            case "学生":
                LambdaQueryWrapper<UsersStu> StuWrapper = new LambdaQueryWrapper<>();
                StuWrapper.eq(UsersStu::getUsersStuId,users.getUsersId());
                UsersStu usersStu=usersStuMapper.selectOne(StuWrapper);
                selectDto.setUserId(usersStu.getUsersStuId().toString());
                selectDto.setPassword(usersStu.getUsersStuPassword());
                selectDto.setCollege(usersStu.getUsersStuInstitute());
                selectDto.setEmail(usersStu.getUsersStuEmail());
                selectDto.setGender(usersStu.getUsersStuGender());
                selectDto.setName(usersStu.getUsersStuName());
                selectDto.setPhone(usersStu.getUsersStuTel());
                selectDto.setMajor(usersStu.getUsersStuMajor());
                selectDto.setClassName(usersStu.getUsersStuClass());
                break;
            case "老师":
                LambdaQueryWrapper<UsersTeacher> thWrapper = new LambdaQueryWrapper<>();
                thWrapper.eq(UsersTeacher::getUsersTeacherId,users.getUsersId());
                UsersTeacher usersTeacher = usersTeacherMapper.selectOne(thWrapper);
                selectDto.setUserId(usersTeacher.getUsersTeacherId().toString());
                selectDto.setPassword(usersTeacher.getUsersTeacherPassword());
                selectDto.setCollege(usersTeacher.getUsersTeacherInstitute());
                selectDto.setEmail(usersTeacher.getUsersTeacherEmail());
                selectDto.setGender(usersTeacher.getUsersTeacherGender());
                selectDto.setName(usersTeacher.getUsersTeacherName());
                selectDto.setPhone(usersTeacher.getUsersTeacherTel());
                break;
            default:
                LambdaQueryWrapper<UsersAdmin> adminWrapper = new LambdaQueryWrapper<>();
                adminWrapper.eq(UsersAdmin::getAdminId,users.getUsersId());
                UsersAdmin usersAdmin = adminUserMapper.selectOne(adminWrapper);
                selectDto.setUserId(usersAdmin.getAdminId().toString());
                selectDto.setName(usersAdmin.getAdminName());

                break;
        }

        return selectDto;

    }

    @Override
    public InfoDto getInfo(BigInteger id) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUsersId,id);
        Users users = userMapper.selectOne(queryWrapper);
        SelectDto all = getAll(users);
        String usersRole = users.getUsersRole();
        all.setUsersRole(usersRole);
        //这里的数组是为了筛选出不需要的字段
        String ignore[]= {"userId","password","className"};
        InfoDto infoDto = new InfoDto();
        BeanUtil.copyProperties(all,infoDto,ignore);
        return infoDto;


    }



    @Override
    public boolean editorSave(SelectDto selectDto,Users users) {
        String usersRole = users.getUsersRole();
        if (selectDto.getGender().equals("male")){
            selectDto.setGender("男");
        }else {
            selectDto.setGender("女");
        }
        switch (usersRole){
            case "学生":
                LambdaQueryWrapper<UsersStu> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UsersStu::getUsersStuId,users.getUsersId());
                UsersStu usersStu = usersStuMapper.selectOne(queryWrapper);
               usersStu.setUsersStuInstitute(selectDto.getCollege());
               usersStu.setUsersStuClass(selectDto.getClassName());
               usersStu.setUsersStuMajor(selectDto.getMajor());
               usersStu.setUsersStuName(selectDto.getName());
               usersStu.setUsersStuGender(selectDto.getGender());
               usersStu.setUsersStuEmail(selectDto.getEmail());
               usersStu.setUsersStuTel(selectDto.getPhone());
                usersStuMapper.update(usersStu,queryWrapper);

                break;
            case "老师":
                LambdaQueryWrapper<UsersTeacher> ThWrapper = new LambdaQueryWrapper<>();
                ThWrapper.eq(UsersTeacher::getUsersTeacherId,users.getUsersId());
                UsersTeacher usersTeacher = usersTeacherMapper.selectOne(ThWrapper);
                usersTeacher.setUsersTeacherId(users.getUsersId());
                usersTeacher.setUsersTeacherPassword(users.getUsersPassword());
                usersTeacher.setUsersTeacherInstitute(selectDto.getCollege());
                usersTeacher.setUsersTeacherName(selectDto.getName());
                usersTeacher.setUsersTeacherGender(selectDto.getGender());
                usersTeacher.setUsersTeacherEmail(selectDto.getEmail());
                usersTeacher.setUsersTeacherTel(selectDto.getPhone());
                usersTeacherMapper.update(usersTeacher,ThWrapper);

                break;
            default:
                LambdaQueryWrapper<UsersAdmin> adminWrapper = new LambdaQueryWrapper<>();
                adminWrapper.eq(UsersAdmin::getAdminId,users.getUsersId());
                UsersAdmin admin = new UsersAdmin();
               admin.setAdminPassword(users.getUsersPassword());
               admin.setAdminName(selectDto.getName());
               adminUserMapper.update(admin,adminWrapper);
                break;
        }
        return true;
    }


    private Users getUserInfo(UserDTO userDTO) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("users_id", userDTO.getUsersId());
        queryWrapper.eq("users_password", userDTO.getUsersPassword());
        Users one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }






    @Override
    public Users register(UserDTO userDTO) {
        Users one = getUserInfo1(userDTO);
        if (one == null) {
            one = new Users();
            BeanUtil.copyProperties(userDTO, one, true);
            save(one);  // 把 copy完之后的用户对象存储到数据库
            add(one);


        } else {
            throw new ServiceException(Constants.CODE_600, "用户已存在");
        }
        return one;
    }
    private void add(Users users){
        if (users.getUsersRole().equals("学生")){
            UsersStu stu = new UsersStu();
            stu.setUsersStuId(users.getUsersId());
            stu.setUsersStuPassword(users.getUsersPassword());
            usersStuMapper.insert(stu);
        }else {
            UsersTeacher teacher = new UsersTeacher();
            teacher.setUsersTeacherId(users.getUsersId());
            teacher.setUsersTeacherPassword(users.getUsersPassword());
            usersTeacherMapper.insert(teacher);
        }
    }

    @Override
    public Users getUserByToken(String token) {
        String tokenWithoutQuotes = token.replace("\"", "");//去除了引号
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(Users::getToken,tokenWithoutQuotes);
        Users users = userMapper.selectOne(queryWrapper);
        return users;

    }



    private Users getUserInfo1(UserDTO userDTO) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("users_id", userDTO.getUsersId());
        Users one;
        try {
            one = getOne(queryWrapper); // 从数据库查询用户信息
        } catch (Exception e) {
            LOG.error(e);
            throw new ServiceException(Constants.CODE_500, "系统错误");
        }
        return one;
    }

    @Override
    public boolean updatePassword(PasswordDto passwordDto) {
        Users users = WebInterceptor.getUsers();
        if (users.getUsersPassword().equals(passwordDto.getOldPassword())){
            Users updateUser = new Users();
            updateUser.setUsersPassword(passwordDto.getNewPassword());
            LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Users::getUsersId,users.getUsersId());
            userMapper.update(updateUser,queryWrapper);
           return true;
        }
      return false;
    }



}



